package b3.model
{
	import b3.net.*;
	import b3.util.*;
	import b3.widget.basic.*;
	
	public class PlayerManager extends Model
	{
		//普通用户
		public static const NORMAL_TYPE:int = 0;
		//管理员id
		public static const MANAGER_TYPE:int = 10;
		//中心商圈id
		public static const CENTER_TYPE:int = 20;
		
		//用户本人的ID
		public var myUserId:int;
		//所有的玩家（用ID作为索引）
		public var players:Object;
		//对话号
		public var sessionId:String;
		
		static private var instance:PlayerManager;
		
		public function PlayerManager()
		{
			players = new Object();
		}
		
		static public function getInstance():PlayerManager
		{
			if (!instance)
				instance = new PlayerManager();
			return instance;
		}
		
		public function get me():Player
		{
			return players[myUserId];
		}
		
		public function loginMeDebug(userId:int):void
		{
			var serverRequest:ServerRequest = new ServerRequest(ServerEvent.LOGIN, {userId:userId});
			serverRequest.setHandleFunc(handleLogin);
			serverRequest.post(true);
		}
		
		public function loginMe():void
		{
			var serverRequest:ServerRequest = new ServerRequest(ServerEvent.LOGIN, {xn_sig_session_key:Profile.xn_sig_session_key});
			serverRequest.setHandleFunc(handleLogin);
			serverRequest.post(true);
		}
		
		public function handleLogin(data:Object):void
		{
			sessionId = data['sessionId'];
			myUserId = data['userInfo']['userId'];
			var me:Player = createPlayer(myUserId);
			me.loadbyObject(data['userInfo']);
			me.logonAwards = new Array();
			var awardData:Object = data['userInfo']['logonAwards'];
			for (var str:String in awardData)
			{
				var obj:Obj = new Obj();
				obj.loadbyObject(awardData[str]);
				me.logonAwards.push(obj);
			}
			dispatchEvent(new ModelEvent(ModelEvent.LOGIN_COMPLETE));
		}
		
		public function createPlayer(playerId:int):Player
		{
			if (players[playerId] != null)
				return players[playerId];
			players[playerId] = new Player(playerId);
			return players[playerId];
		}
		 
		/**
		 * 同步人口（按街区）
		 */
		public function syncPopulation(userId:int, sectionIndex:int, force:Boolean = false):void
		{
		 	var serverRequest:ServerRequest = new ServerRequest(ServerEvent.SYNC_POPULATION, {ownerId:userId, sectionIndex:sectionIndex});
			serverRequest.setHandleFunc(handleSyncPopulation);
			serverRequest.post(force);
		}
		 
		/**
		 * 处理人口同步信息
		 */
		private function handleSyncPopulation(data:Object):void
		{
		 	//更新本人信息	
		 	me.handleLoadPlayerInfo(data['userInfo']);
		 	//更新包裹信息
		 	me.packageModel.handleLoadObjects(data['package']);
			//检测是否完成建设任务
			me.taskList.checkAndFinishBuildTask();
			
			if (data['townOwnerPackage'] != null)
			{
				var townOwnerId:int = data['townOwnerPackage']['ownerId'];
				(players[townOwnerId] as Player).packageModel.handleLoadObjects(data['townOwnerPackage']);
			}
		}
	}
}